package org.dreamwork.tools.network.bridge.client.fx.controllers;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import org.dreamwork.concurrent.Looper;
import org.dreamwork.config.KeyValuePair;
import org.dreamwork.tools.network.bridge.client.Keys;
import org.dreamwork.tools.network.bridge.client.fx.GuiContext;
import org.dreamwork.util.StringUtil;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * Created by seth.yang on 2020/3/9
 */
public class AbstractController implements Initializable {

    private static final URL icon =
            AbstractController.class.getClassLoader ().getResource ("images/64x64/route.png");

    protected Stage stage;

    public Stage getStage () {
        return stage;
    }

    public void setStage (Stage stage, String title) {
        this.stage = stage;
        if (stage != null && icon != null) {
            try {
                stage.getIcons ().add (new Image (icon.openStream ()));
            } catch (Exception ex) {
                ex.printStackTrace ();
            }

            if (!StringUtil.isEmpty (title)) {
                stage.setTitle (title);
            }

            stage.setOnCloseRequest (e->onDispose ());
        }
    }

    /**
     * Called to initialize a controller after its root element has been
     * completely processed.
     *
     * @param location  The location used to resolve relative paths for the root object, or
     *                  <tt>null</tt> if the location is not known.
     * @param resources The resources used to localize the root object, or <tt>null</tt> if
     */
    @Override
    public void initialize (URL location, ResourceBundle resources) {
        System.out.printf ("%n[%s] Am i re-invoke?%n%n", getClass ().getName ());
    }

    protected void onDispose () {}

    @FXML protected void cancel () {
        if (stage != null) {
            stage.close ();
            stage = null;
        }
    }

    protected String getResource (String key, KeyValuePair<?>... params) {
        return GuiContext.getResource (key, params);
    }

    protected String getResource (String key, String paramName, String paramValue) {
        return GuiContext.getResource (key, paramName, paramValue);
    }

    protected void post (Runnable runner) {
        if (Platform.isFxApplicationThread ())
            runner.run ();
        else
            Platform.runLater (runner);
    }

    protected void background (Runnable runner) {
        Looper.runInLoop (Keys.UI.KEY_UI_BG_THREAD, runner);
    }
}
